package main

import (
	"fmt"
	"net"

	"gitee.com/cyberocx/rpc-server/biz/mw"

	"gitee.com/cyberocx/rpc-server/biz/service"
	"gitee.com/cyberocx/rpc-server/pb/rpc-server/kitex_gen/rpc_server/rpcserverservice"
	"github.com/cloudwego/kitex/pkg/klog"
	"github.com/cloudwego/kitex/pkg/limit"

	"github.com/cloudwego/kitex/pkg/registry"
	"github.com/cloudwego/kitex/pkg/rpcinfo"
	"github.com/cloudwego/kitex/server"
	"github.com/hashicorp/consul/api"
	consul "github.com/kitex-contrib/registry-consul"

	"gitee.com/cyberocx/rpc-server/biz/conf"
	"gitee.com/cyberocx/rpc-server/biz/dal"
)

func main() {
	conf.Init()
	dal.Init()

	addr, _ := net.ResolveTCPAddr("tcp", getAddr())
	reg := register()
	opts := []server.Option{
		server.WithRegistry(reg),
		server.WithServiceAddr(addr),
		server.WithLimit(
			&limit.Option{
				MaxConnections: conf.Config.Server.RateLimit.MaxConn,
				MaxQPS:         conf.Config.Server.RateLimit.MaxQps,
			},
		),
		server.WithServerBasicInfo(
			&rpcinfo.EndpointBasicInfo{
				ServiceName: conf.Config.Server.Service.Name,
			},
		),
		server.WithMiddleware(mw.AccessLogMiddleware),
	}

	svr := rpcserverservice.NewServer(newHandler(), opts...)
	if err := svr.Run(); err != nil {
		klog.Error(err.Error())
	}
}

func newHandler() *service.Service {
	return &service.Service{}
}

func register() registry.Registry {
	var (
		reg registry.Registry
		err error
	)
	regConf := conf.Config.Registry
	switch regConf.Type {
	case "consul":
		consulConfig := api.Config{
			Address: regConf.Address,
			Token:   regConf.Token,
		}
		reg, err = consul.NewConsulRegisterWithConfig(&consulConfig)
		if err != nil {
			klog.Fatal(err)
		}
	default:
		klog.Fatalf("unsupported registry type: %s", regConf.Type)
	}
	return reg
}

func getAddr() string {
	return fmt.Sprintf(
		"%s:%d", conf.Config.Server.Service.Address,
		conf.Config.Server.Service.Port,
	)
}
